package com.then.basic.socket.core;

import java.security.InvalidParameterException;


import android.util.Log;

import com.then.basic.socket.BuildConfig;
import com.then.basic.socket.SocketConfig;
import com.then.basic.socket.data.ProtocolCode;
import com.then.basic.socket.utils.DataUtil;
import com.then.basic.socket.utils.I366PickUtil;

/**
 * class for parsing request
 */
public class ClientRequest {
    private static final String TAG = "ClientRequest";

    private int requestCode;
    private BaseCommData commData; // parsed data info

    public int getRequestCode() {
        return requestCode;
    }

    public BaseCommData getBody() {
        return commData;
    }

    public ClientRequest(byte[] data) {
        parse(data);
    }

    protected void setRequestCode(int requestCode) {
        this.requestCode = requestCode;
    }

    /**
     * parse the bytes array
     * @param contents the byte array contains all the data
     */
    private void parse(byte[] contents) {
        requestCode = DataUtil.byteArrayToShortInt(contents, SocketConfig.SRP_REQUEST_HIGH);
        parseCommand(contents);
    }

    // translate the contents to the communication object
    private BaseCommData processRequest(byte[] contents) {
        BaseCommData.BaseCommClassInfoCache processor = BaseCommData.getCommClassInfoCache(requestCode);
        if (processor == null) {
            return null;
        }

        BaseCommData msgObj = I366PickUtil.pickAll(contents, processor);
        if (msgObj != null) {
            return msgObj;
        } else if (BuildConfig.DEBUG) {
            throw new InvalidParameterException("Parse data error. requestCode:" + requestCode);
        } else {
            Log.e(TAG, "Parse data error!");
        }
        return null;
    }

    // parse the request
    private void parseCommand(byte[] contents) {
        Log.i(TAG, "server code:" + requestCode);

        commData = processRequest(contents);
        // 过滤心跳包
        if (commData == null && requestCode != ProtocolCode.REQ_SIGNAL_RESOURCE && requestCode != ProtocolCode.REQ_SIGNAL_GAME) {
            Log.w(TAG, "package handler not found! package type:" + requestCode);
        }
    }
}

